package com.gzcssutils;

import com.bean.WeiXinUser;
import com.bean.UserTicket;
import cn.hutool.json.JSONObject;
import java.util.logging.Logger;


public class AccessUserInfo {

    public final static String get_user_ticket_url = "http://address:port/cgi-bin/user/getuserinfo?access_token=ACCESS_TOKEN&code=CODE";

    public final static String get_user_detail = "http://address:port/cgi-bin/user/get?access_token=ACCESS_TOKEN&userid=USERID";

    private static Logger log = Logger.getLogger("com.utils.AccessUserInfo");


    /**
     * 获取user_ticket
     *
     * @param code 政务微信端返回的唯一用户凭证
     * @return 用户的Ticket
     */
    public static UserTicket getUserTicket(String code) {
        UserTicket ticket = new UserTicket();
        String requestTicketUrl = "";
        JSONObject ticketObject;

        String ipPort = Constant.url;
        requestTicketUrl = get_user_ticket_url.replace("address:port", ipPort).replace("ACCESS_TOKEN", AccessTokenThread.getCacheToken())
                .replace("CODE", code);
        log.info("取得 requestTicketUrl URL:" + requestTicketUrl);
        ticketObject = HttpUtil.httpRequest(requestTicketUrl, "GET", null);

        String errorCode = ticketObject.get("errcode").toString();

        String errorMsg = ticketObject.get("errmsg").toString();
        log.info("获取ticket,errcode=" + errorCode + ",errmsg=" + errorMsg);

        ticket.setUserid(ticketObject.getStr("UserId"));
        ticket.setDeviceid(ticketObject.getStr("DeviceId"));
        return ticket;
    }

    /**
     * 获取企业微信用户信息
     *
     * @param userId 手机号
     * @return 用户信息
     */
    public static WeiXinUser getUser(String userId) {

        WeiXinUser userInfo = new WeiXinUser();
        String ipPort = Constant.url;
        String requestUserInfoUrl = get_user_detail.replace("address:port", ipPort)
                .replace("ACCESS_TOKEN", AccessTokenThread.getCacheToken()).replace("USERID", userId);
        log.info("取得 requestUserInfoUrl URL:" + requestUserInfoUrl);

        JSONObject jsonObject = HttpUtil.httpRequest(requestUserInfoUrl, "GET", null);

        userInfo.setUserid(jsonObject.getStr("userid"));
        userInfo.setName(jsonObject.getStr("name"));
        userInfo.setPosition(jsonObject.getStr("position"));
        userInfo.setMobile(jsonObject.getStr("mobile"));
        userInfo.setGender(jsonObject.getInt("gender"));
        userInfo.setEmail(jsonObject.getStr("email"));
        userInfo.setAvatar(jsonObject.getStr("avatar"));
        return userInfo;
    }
}
